import axios from 'axios'
import { ElMessage } from 'element-plus'

class Uploader {
  static #instance
  #baseURL
  
  constructor() {
    if (!import.meta.env.VITE_API_BASE_URL) {
      console.warn('VITE_API_BASE_URL is not defined in environment variables')
    }
    this.#baseURL = import.meta.env.VITE_API_BASE_URL?.trim() || 
                   (import.meta.env.MODE === 'production' ? '/api' : 'http://localhost:127.0.0.1::9502/api')
  }

  static getInstance() {
    if (!Uploader.#instance) {
      Uploader.#instance = new Uploader()
    }
    return Uploader.#instance
  }

  async upload(file, type = 'image', onProgress) {
    const formData = new FormData()
    formData.append('img', file)
    formData.append('type', type)

    try {
      const { data } = await axios.post(`${this.#baseURL}/common/uploadImg`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': 'Bearer '+localStorage.getItem('Authorization') || ''
        },
        onUploadProgress: (progressEvent) => {
          if (onProgress && progressEvent.total) {
            const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            onProgress(percent)
          }
        }
      })
      return data.data.url
    } catch (error) {
      ElMessage.error('上传失败: ' + error.message)
      throw error
    }
  }

  async uploadImageWithCompression(file, quality = 0.8, maxWidth = 1920) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = async (event) => {
        try {
          const img = new Image()
          img.src = event.target?.result
          
          img.onload = async () => {
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            
            let width = img.width
            let height = img.height
            if (width > maxWidth) {
              height = (maxWidth / width) * height
              width = maxWidth
            }
            
            canvas.width = width
            canvas.height = height
            ctx.drawImage(img, 0, 0, width, height)
            
            canvas.toBlob(async (blob) => {
              if (!blob) {
                reject(new Error('图片压缩失败'))
                return
              }
              
              const compressedFile = new File([blob], file.name, {
                type: 'image/jpeg',
                lastModified: Date.now()
              })
              
              const url = await this.upload(compressedFile, 'image')
              resolve(url)
            }, 'image/jpeg', quality)
          }
        } catch (error) {
          reject(error)
        }
      }
      reader.readAsDataURL(file)
    })
  }
}

export default Uploader.getInstance()